package com.Jian.reggie.controller;

import com.Jian.reggie.common.BaseContext;
import com.Jian.reggie.common.R;
import com.Jian.reggie.impl.AddressBook;
import com.Jian.reggie.service.AddressBookService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: addressBook
 * Package: com.Jian.reggie.controller
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/29 14:48
 * @Version 1.0
 */
@Slf4j
@RequestMapping("/addressBook")
@RestController
public class AddressBookController {
  @Autowired
  private AddressBookService addressBookService;
  
  @GetMapping("/default")
  public R<AddressBook> getDefaultAddress() {
    Long currentUserId = BaseContext.getCurrentId();
    LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(AddressBook::getUserId, currentUserId).eq(AddressBook::getIsDefault, 1);
    
    AddressBook one = addressBookService.getOne(wrapper);
    return R.success(one);
  }
  
  /**
   * 查询当前用户的所有地址
   */
  @GetMapping("/list")
  public R<List<AddressBook>> list() {
    LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
    Long currentUserId = BaseContext.getCurrentId();
    wrapper.eq(AddressBook::getUserId, currentUserId);
    
    List<AddressBook> list = addressBookService.list(wrapper);
    return R.success(list);
  }
  
  /**
   * 新增地址
   */
  @PostMapping
  public R<String> add(@RequestBody AddressBook addressBook) {
    Long currentUserId = BaseContext.getCurrentId();
    addressBook.setUserId(currentUserId);
    addressBookService.save(addressBook);
    return R.success("新增地址成功");
  }
  
  /**
   * 修改默认地址
   */
  @PutMapping("/default")
  public R<String> updateDefault(@RequestBody AddressBook addressBook) {
    Long currentUserId = BaseContext.getCurrentId();
    LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(AddressBook::getUserId, currentUserId);
    List<AddressBook> list = addressBookService.list(wrapper);
    List<AddressBook> collect = list.stream().peek(item -> {
      if (item.getId().equals(addressBook.getId())) {
        item.setIsDefault(1);
      } else {
        item.setIsDefault(0);
      }
    }).toList();
    addressBookService.updateBatchById(collect);
    
    return R.success("修改默认地址成功");
  }
}
